﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using HorseRaceTracker.Domain.Core;

namespace HorseRaceTracker.Infrastructure.ADO.NET
{
    public class CountryFetcher
    {
        private List<Country> _countries;

        public CountryFetcher()
        {
            _countries = new List<Country>();
        }
        public Country RetrieveByCode(string code)
        {
            var country = _countries.SingleOrDefault(c => c.Code.ToUpperInvariant() == code.ToUpperInvariant());
            if (country != null)
            {
                return country;
            }
            else
            {
                var countryDb = new Country();
                using (var sqlConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DataServices"].ConnectionString))
                {
                    sqlConnection.Open();
                    using (
                        var cmd =
                            new SqlCommand("SELECT CountryCode, Country  FROM Country where CountryCode = @CountryCode",
                                           sqlConnection))
                    {

                        cmd.Parameters.AddWithValue("CountryCode", code);
                        using (var reader = cmd.ExecuteReader(CommandBehavior.Default))
                        {
                            if (reader != null)
                            {
                                while (reader.Read())
                                {
                                   
                                    countryDb.Code = code;
                                    countryDb.Name = reader.GetString(1);
                                    _countries.Add(countryDb);
                                   
                                }
                            }
                        }
                    }
                }
                return countryDb;
            }
        }
    }
}
